<?php

namespace backend\models;

use Yii;
use backend\models\SchoolCertificate;

class School extends \common\models\School
{
    public function rules()
    {
        return array_merge([
            [['DM', 'DZDM', 'SDJYBMDM', 'XZQHM', 'FRZSH'], 'match', 'pattern' => '/^[a-zA-Z0-9]+$/','message' => '该项填写内容包含非法字符'],  // 代号类字段
            [['FZRLXDH', 'LXDH', 'CZDH', 'XZSJH', 'XJLXDH', 'ZSZXDH'], 'match', 'pattern' => '/^(\(\+?\d{2,4}\))?(\d{4}-)?\d+$/','message' => '号码格式不正确'],  // 电话号码类字段
            [['DZXX', 'ZSZXYX'], 'email'],
            [['JXNY'], 'date', 'format' => 'php:Y-m', 'message' => '错误的日期格式，请重新修改'],
            [['JXNY'], 'filter', 'filter' => function($value) { return $value.'-01'; }],
            [['YWMC'], 'match', 'pattern' => '/^[a-zA-Z0-9\s]+$/', 'message' => '字符类型超出限制'],
            [['ZYDZ'], 'url', 'message' => '非法网址格式，请重新修改'],
            [['FZRLXDH', 'LXDH', 'CZDH', 'XJLXDH', 'ZSZXDH', 'XZSJH'], 'string', 'length' => [7, 16], 'message' => '电话号码过长或过短'],
            [['YZBM'], 'string', 'length' => 6, 'message' => '邮编是6位数字'],
            [['YZBM'], 'match', 'pattern' => '/^\d+$/','message' => '该项填写内容应为纯数字'],  // 纯数字类字段
            [['SSMZXX', 'SFJLXYW'], 'boolean', 'strict' => false, 'message' => '此项只能填1或0，其中1为是0为否'],
            [['ZT'], 'default', 'value' => '修改'],
        ], parent::rules());
    }

    /////////////// 生成/获取影子记录 ///////////////
    public function getShadowRecord($model)
    {
        $result = School::find()->select('ID')->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one();          
             
        if (!$result) // 无影子记录->新创建
        {
            $newModel = new School();
            $newModel->load(Yii::$app->request->post());
            $newModel->save();

            // 同时生成一条school-certificate的影子记录
            $noumenonID = School::find()->select('ID')->where("DM = '$model->DM'")->andWhere("ZT = '正常'")->one()['ID'];
            $shadowID = School::find()->select('ID')->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one()['ID'];
            $certificateRecord = SchoolCertificate::find()->where("XXID = '$noumenonID'")->one();   // 查找本体记录对应的school-certificate记录
            $recordAsArray = $certificateRecord->attributes;  // 提取证照资质记录的数组数据
            unset($recordAsArray['ID']);  // 删除证照资质记录的数组数据中的ID字段，使新纪录ID可以自增
            $newCertificateRecord = new SchoolCertificate( $recordAsArray );  // 生成证照资质的影子记录
            $newCertificateRecord->XXID = $shadowID;  // 修改影子记录的XXID为school表相应的ID
            $newCertificateRecord->save();
        }
        else  // 已存在影子记录
        {
            $model->update();  // 在提交审核之前的任意次修改依然生效
        }

        $result = School::find()->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one();
        return $result;
    }

    /////////////// 获取本体记录 ///////////////
    public function getNoumenonRecord($model)
    {
        $noumenon = $model->find()->where("DM = '$model->DM'")->andWhere("ZT = '正常'");
        if($noumenon->exists())
        {
            // 有本体记录
            // return $this->findModel($noumenon->one()->ID);
            return $noumenon->one();
        }
        else
        {
            return NULL;
        }
    }

    /////////////// 审核通过后更新记录（返回更新后的本体记录）///////////////
    public function updateRecord($model)
    {
        $noumenon = School::getNoumenonRecord($model);  // 查找本体记录

        if($noumenon)   // 有本体记录
        {
            $noumenonID = $noumenon->ID;
            foreach ($noumenon as $k => $v) {
                $noumenon->$k = $model->$k;
            }
            $noumenon->ID = $noumenonID;
            $noumenon->XGYJ = NULL;            
            
            // 删除影子记录
            $model->delete();
        }
        else  // 无本体记录
        {           
            $noumenon = $model;
        }

        $noumenon->XGYJ = NULL;
        $noumenon->ZT = '正常';
        $noumenon->update(false);

        return $noumenon;
    }

    /////////////// 判断是否存在影子记录 ///////////////
    // 只有当查询的记录本身是本体记录且同时存在影子记录时返回true
    public function hasShadowRecord()
    {
        if ($this->ZT != '正常') return false;
        return (bool)(School::find()->where("DM = '$this->DM'")->andWhere(['not', "ZT = '正常'"])->asArray()->one());
    }

    /////////////// 判断是否存在待审核的影子记录 ///////////////
    // 只有当查询的记录本身是本体记录且同时存在影子记录时返回true
    public function _hasShadowRecord()
    {
        if ($this->ZT != '正常') return false;
        return (bool)(School::find()->where("DM = '$this->DM'")->andWhere("ZT = '待审核'")->asArray()->one());
    }

    /////////////// 判断是否存在本体记录 ///////////////
    // 只有当查询的记录本身是影子记录且同时存在本体记录时返回true
    public function hasNoumenonRecord()
    {
        if ($this->ZT == '正常') return false;
        return (bool)(School::find()->where("DM = '$this->DM'")->andWhere("ZT = '正常'")->asArray()->one());
    }

    /////////////// 表格行渲染规则 ///////////////
    public function showTableRows($model)
    {
        if($model->ZT == '修改') return 'none';
        $flag = School::find()->where("DM = '$model->DM'")->andWhere("ZT = '待审核'")->one();
        if($model->ZT == '正常' && $flag) return 'none';
    }

    //提供关联数组 ID => XXID, 可用于下拉框
    public static function getSchoolID($school_id = null)
    {
        $query=self::find()->select(['ID'])->orderBy('ID')->indexBy('ID');
        // if($school_id)
        // {
        //     $query->andWhere(['ID' => $school_id]);
        // }
        return $query->column();
    }
}